package com.starbaba.activityCommend.service.impl;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.starbaba.activityCommend.model.LoanActivityModel;
import com.starbaba.activityCommend.model.LoanAdvertModel;
import com.starbaba.activityCommend.service.LoanAdvertService;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.model.dictionary.Constant;

/**
 * 贷款产品管理
 * @version 1.0
 */
@Component
public class LoanAdvertServiceImpl implements LoanAdvertService {
    
	@SuppressWarnings("deprecation")
    private static BaseDao dao = new BaseDao(Constant.POOL_LIFE);
	
    @Override
    @SuppressWarnings("rawtypes")
	public List<LoanAdvertModel> getDataList(int iDisplayStart, int iDisplayLength, PageResponse pageResponse, Map<String, Object> paramsMap) {
        
        String platform = (String) paramsMap.get("platform");
		String prdid = (String) paramsMap.get("prdid");
		String channel = (String) paramsMap.get("channel");
		String tag = (String) paramsMap.get("tag");
		String status = (String) paramsMap.get("status");
		String advert_space = (String) paramsMap.get("advert_space");
		String activity_name = (String) paramsMap.get("activity_name");
		String sql = "select c.id,c.platform,c.prdid,c.channel,c.position,"
		           + "DATE_FORMAT(c.startTime, '%Y-%m-%d %H:%i:%s') AS startTime,"
				   + "DATE_FORMAT(c.endTime, '%Y-%m-%d %H:%i:%s') AS endTime,"
		           + "c.status,c.activity_id,c.suggest,c.ctime,c.utime,c.operator,c.remark,c.tag,c.advert_space from loan.loan_advert c";
		
		if (!StringUtils.isEmpty(activity_name)) {
			sql += ",loan.loan_product_info d";
		}
		sql += " where 1=1 and show_state=1";
		
		String selectSql = "";
		if (!StringUtils.isEmpty(platform)) {
			
            selectSql += " and c.platform = " + Integer.parseInt(platform) ;
        }
		if (!StringUtils.isEmpty(prdid)) {
			selectSql += " and (c.prdid like '%" + prdid + "%' or c.prdid = 0 )" ;
		}
		if (!StringUtils.isEmpty(channel)) {
            selectSql += " and c.channel = " + Integer.parseInt(channel) ;
        }
		if (!StringUtils.isEmpty(tag)) {
            selectSql += " and c.tag like '%" + tag + "%'" ;
        }
		if (!StringUtils.isEmpty(status)) {
            selectSql += " and c.status = " + Integer.parseInt(status) ;
        }
		if (!StringUtils.isEmpty(advert_space)) {
            selectSql += " and c.advert_space = " + Integer.parseInt(advert_space) ;
        }
		if (!StringUtils.isEmpty(activity_name)) {
			selectSql += " and c.activity_id = d.id and d.name like '%" + activity_name + "%'";
		}

		sql += selectSql;
		sql += " order by c.position asc limit " + iDisplayStart + " , " + iDisplayLength;

		String countSql = "select count(1) from loan_advert c ";
		if (!StringUtils.isEmpty(activity_name)) {
			countSql += ",loan.loan_product_info d ";
		}
		countSql += " WHERE 1=1 and show_state = 1 " + selectSql;
		
		List<LoanAdvertModel> list = null;
		try {
			String sqltemp = "select id,name from loan_product_info";
			List<LoanActivityModel> listtemp = dao.list(sqltemp, LoanActivityModel.class, new Object[] {});
			int count = dao.getInt(countSql);
			list = dao.list(sql, LoanAdvertModel.class, new Object[] {});
			
			for(LoanAdvertModel advertModel : list){
				for(LoanActivityModel activityModel : listtemp){		
					
					if(Integer.parseInt(advertModel.getActivity_id().toString()) == activityModel.getId()){
						advertModel.setActivity_name(activityModel.getName());
					}	
				}
			}
			pageResponse.setITotalRecords(count);
			pageResponse.setITotalDisplayRecords(count);
		} catch (AppException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public Long save(Map<String, Object> paramsMap, LoanAdvertModel bean) {

		//String countsql = "select position+1 from loan_advert ";
		
		LoanAdvertModel model = setValue(bean);
		Long id = null;
		
		SimpleDateFormat tempFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = tempFormat.format(new Date());
        model.setCtime(date);
        
		//int position = 0;
		try {
			//position = dao.getInt(countsql, new Object[] {});
			//model.setPosition(position);
			id = dao.addReturnGeneratedKey(model);
			return id;
		} catch (AppException e) {
			e.printStackTrace();
			return 0L;
		}
	}

	public LoanAdvertModel setValue(LoanAdvertModel bean) {

		LoanAdvertModel model = null;
		try {
			model = new LoanAdvertModel();

			model.setPlatform(bean.getPlatform());
			model.setPrdid(bean.getPrdid());
			model.setChannel(bean.getChannel());
			model.setPosition(bean.getPosition());
			model.setStatus(bean.getStatus());
			model.setActivity_id(bean.getActivity_id());
			model.setPosition(bean.getPosition());
			model.setAdvert_space(bean.getAdvert_space());
			model.setOperator(bean.getOperator());
			model.setIs_timer(bean.getIs_timer());
			model.setRedirect_type(bean.getRedirect_type());
			
			//修改时间
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = format.format(new Date());
			model.setUtime(date);
			
			if (StringUtils.isNotEmpty(bean.getStartTime())) {
				model.setStartTime(bean.getStartTime());
			}
			
			if (StringUtils.isNotEmpty(bean.getEndTime())) {
				model.setEndTime(bean.getEndTime());
			}
			
			if(StringUtils.isNotEmpty(bean.getOperator())){
				model.setOperator(bean.getOperator());
			}
			
			if((StringUtils.isNotEmpty(bean.getTag()))){
				model.setTag(bean.getTag());
			}
			
			if((StringUtils.isNotEmpty(bean.getExclude_channel()))){
				model.setExclude_channel(bean.getExclude_channel());
			}
			
			if (StringUtils.isNotEmpty(bean.getFixed_start_time())) {
				model.setFixed_start_time(bean.getFixed_start_time());
			}
			
			if (StringUtils.isNotEmpty(bean.getFixed_end_time())) {
				model.setFixed_end_time(bean.getFixed_end_time());
			}			
			
			if(Objects.nonNull(bean.getUpper_limit())) {
				model.setUpper_limit(bean.getUpper_limit());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return model;
	}

	@Override
	public void update(Map<String, Object> paramsMap, LoanAdvertModel bean) {
		
		LoanAdvertModel model = setValue(bean);
		model.setId(bean.getId());
		try {
			model.setId(bean.getId());
			dao.update(model, new String[]{"id"});
			
			if (StringUtils.isEmpty(bean.getFixed_end_time())) {
				dao.update("update loan_advert set fixed_end_time = null where id = ?", bean.getId());
			}
			
			if (StringUtils.isEmpty(bean.getFixed_start_time())) {
				dao.update("update loan_advert set fixed_start_time = null where id = ?", bean.getId());
			}
			
			if (StringUtils.isEmpty(bean.getStartTime())) {
				dao.update("update loan_advert set starttime = null where id = ?", bean.getId());
			}
			
			if (StringUtils.isEmpty(bean.getEndTime())) {
				dao.update("update loan_advert set endtime = null where id = ?", bean.getId());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			LogService.error(e);
		}
	}
}
